//
//  SEChatVoiceIndicatorView.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/5/6.
//

import UIKit

class SEChatVoiceIndicatorView: UIView {

    @IBOutlet private weak var containerView: UIView! {
        didSet {
            containerView.layer.cornerRadius = 4
            containerView.layer.masksToBounds = true
        }
    }
    
    @IBOutlet private weak var recordingView: UIView!
    
    @IBOutlet private weak var noteLabel: UILabel! {
        didSet {
            noteLabel.layer.cornerRadius = 2
            noteLabel.layer.masksToBounds = true
        }
    }
    
    @IBOutlet private weak var cancelImageView: UIImageView!
    @IBOutlet private weak var signalValueImageView: UIImageView!
    @IBOutlet private weak var voiceTooShortImageView: UIImageView!
    
    private var imageArr = [UIImage]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    private func setup() {
        var imageArr = [UIImage]()
        for i in 1...8 {
            let imageName = "icon_recording_signal_00\(i)"
            let image = UIImage(named: imageName)!
            imageArr.append(image)
        }
        self.imageArr = imageArr
    }
}

extension SEChatVoiceIndicatorView {
    /// 正在录音
    func recording() {
        isHidden = false
        cancelImageView.isHidden = true
        voiceTooShortImageView.isHidden = true
        recordingView.isHidden = false
        noteLabel.backgroundColor = .clear
        noteLabel.text = "手指上滑，取消发送"
    }
    
    /// 滑动取消
    func slideToCancelRecord() {
        isHidden = false
        cancelImageView.isHidden = false
        voiceTooShortImageView.isHidden = true
        recordingView.isHidden = true
        noteLabel.backgroundColor = UIColor(hex: "#9C3638")
        noteLabel.text = "松开手指，取消发送"
    }
    
    /// 语音太短
    func voiceTooShort() {
        isHidden = false
        cancelImageView.isHidden = true
        voiceTooShortImageView.isHidden = false
        recordingView.isHidden = true
        noteLabel.backgroundColor = .clear
        noteLabel.text = "说话时间太短"
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.endRecord()
        }
    }
    
    /// 结束录音
    func endRecord() {
        isHidden = true
    }
    
    /// 更新麦克风的音量大小
    func updateMetersValue(_ value: Float) {
        var index = Int(round(value))
        index = index < 0 ? 0 : (index > 7 ? 7 : index)
        self.signalValueImageView.image = imageArr[index]
    }
}
